package com.kb.spring.jpa.service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.kb.spring.jpa.dao.PersonJpaSpecificationRepository;
import com.kb.spring.jpa.entities.Person;

@Service
public class PersonJpaSpecificationService {
	@Autowired
	private PersonJpaSpecificationRepository personJpaSpecificationRepository;
	
	public void testJpaSpecificationRepository(){
		int pageNo = 3 - 1;
		int pageSize = 5;
		PageRequest pageable = new PageRequest(pageNo, pageSize);
		
		//通常使用Specification的匿名内部类
		Specification<Person> specification = new Specification<Person>() {
			/**
			 * root ： 代表查询实体类
			 * query ： 可以从中得到Root对象,即告知JPA Criteria查询要查询哪一个实体类,还可以来添加
			 * 查询条件,还可以结合EntityManager对象得到最终查询的TypedQuery对象。
			 * cb : CriteriaBuilder对象,用于创建Criteria相关对象的工厂,当然可以从中获取到Predicate对象
			 * Predicate 类型 ,代表一个查询条件
			 */
			@Override
			public Predicate toPredicate(Root<Person> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				Path path = root.get("id");
				Predicate predicate = cb.gt(path,1005);
				return predicate;
			}
		};
		Page<Person> pageAll = personJpaSpecificationRepository.findAll(specification, pageable);
		System.out.println("总记录数: " + pageAll.getTotalElements());
		System.out.println("当前第几页: " + (pageAll.getNumber() + 1));
		System.out.println("总页数: " + pageAll.getTotalPages());
		System.out.println("当前页面内容 " + pageAll.getContent());
		System.out.println("当前页面的总记录数: " + pageAll.getNumberOfElements());
	}
}
